/**
 * 集成ext datagrid控件，实现datagrid和建模工具的集成，实现增，删，改，查的功能以及其他集成方式
 * 作者：xuqiang
 * 日期：2016-10-12
 * 版本：1.0
*/
Ext.namespace("Ext.com.bkfm")
Ext.define('Ext.com.bkfm.datagrid', {
	extend:"Ext.grid.GridPanel",
	//id : "grid_" + Ext.id(),
	//width : 400,
	//height : 300,
	autoScroll : false,
	//默认显示标准按钮，用户可以不需要重新定义按钮
	showstandardBtn: true,
	//自定义工具栏按钮
	customBtn: [],
	//是否自动加载数据，默认为自动加载
	loadAuto: true,
	// 模板名称
	objPath : '',
	//
	saveObjPath: null,
	// 查询过滤条件 以 and 开始
	filter : '',
	//排序order by field asc
	orderby: '',
	// 默认列宽
	fieldWidth : 150,
	// 每页显示条数
	pageSize : 30,
	// 分页工具条
	paging : true,
	// 是否显示行号
	showRowNum : true,
	// 是否显示复选框
	checked : true,
	//选择方式，multi,simple,single；默认为多选multi
	checkMode: 'multi',
	//如果值为true，则只用点击checkbox列才能选中此条记录,否则点击行也可以选中
	checkBoxOnly: false,
	// 显示边框
	frame : false,//边框默认存在
	//隐藏的字段数组['FIELD']必须大写
	hiddenField: [],
	// 表单建模属性
	//columnMeta : null,
	// 存储表头信息
	columnHeaderMeta : null,
	// 表格数据映射记录
	columnFields : null,
	// 自定义列
	userConfigColumn : null,
	//高级查询面板查询值字段
	queryColumnField: null,
	//是否可编辑，默认为不可编辑
	gridEditor: false,
	//是否展示统计
	statistics: false,
	//展示统计的字段
	statisticsField: {},
	//通用表单显示页面不需要创建的字段
	formUnViewField: null,
	//初始化
	initComponent: function(){
		if(Ext.isEmpty(this.objPath)){
			AjaxUtils.showError('创建表格异常，无效的存储参数');
			Ext.com.bkfm.datagrid.superclass.initComponent.call(this);
			return;
		}

		this.getServiceModelMeta();
		/**
		 * 添加渲染之后事件
		 */
		if(this.showstandardBtn){
			this.createToolBar();
		}
		/**
		 * 是否展示统计
		 */
		if(this.statistics){
			this. features=[{
                ftype: 'summary'
            }];
		}
		this.callParent(arguments);
	},
	//获取服务器建模属性
	getServiceModelMeta: function(){
		var grid = this;
		AjaxUtils.CallJsonService({
			url: CONTEXT.contextPath+"/bkfm/metadata/v1/querytablemetacolumn",
			params: {
				"obj_path": grid.objPath
			},
			call: function(data){
				grid.createColumnMeta(data);
				grid.callSuperStrunct();
				grid.addEditorPlugins();
			}
		});
	},
	callSuperStrunct: function(){
		//获取表格数据,加载远程数据
		this.store = this.getGridStoreData();

		// 生成表格header头
		this.columns = this.columnHeaderMeta;

		//创建分页
		this.paddingInfo();

	},
	/**
	 * 创建工具栏按钮
	 */
	createToolBar: function(){
		var grid = this;
		var toobar = ['->'];
		//var page_index = Utils.getReqParams("rwid");
		//新建
		if(Utils.hasModelBtnPermis(grid.objPath,"new")){
			toobar.push({
				text : '新建',
				iconCls : 'add',
				handler : function() {
					grid.showEditorForm("add");
				}
			});
		}
		//编辑
		if(Utils.hasModelBtnPermis(grid.objPath,"edit")){
			toobar.push({
				text: '编辑',
				iconCls: 'edit',
				handler: function(){
					var r = grid.getSelectedRecords();
					if(!r || r.length ==0){
						return;
					}
					grid.showEditorForm("edit",r[0]);
				}
			});
		}
		//查看
		if(Utils.hasModelBtnPermis(grid.objPath,"view")){
			toobar.push({
				text: '查看',
				iconCls: 'view',
				handler: function(){
					var r = grid.getSelectedRecords();
					if(!r || r.length ==0){
						return;
					}
					grid.showEditorForm("view",r[0]);
				}
			});
		}
		//删除
		if(Utils.hasModelBtnPermis(grid.objPath,"del")){
			toobar.push({
				text: '删除',
				iconCls: 'delete',
				handler: function(){
					grid.deleteRecords(grid.afterDeleteRecords);
				}
			});
		}
		//删除
		if(Utils.hasModelBtnPermis(grid.objPath,"search")){
			toobar.push('-',{
				text: '高级查询',
				iconCls: 'adsearch',
				handler: function(){
					grid.customizeQuery();
				}
			});
		}
		//导出
		if(Utils.hasModelBtnPermis(grid.objPath,"exp")){
			toobar.push('-',{
				text: '导出',
				iconCls: 'export',
				handler: function(){
					grid.exportGridDate();
				}
			});
		}
		//导入
		if(Utils.hasModelBtnPermis(grid.objPath,"imp")){
			toobar.push('-',{
				text: '导入',
				iconCls: 'import',
				handler: function(){
					grid.importGridData();
				}
			});
		}
		//合并自定义按钮和基础功能按钮
		this.tbar = Ext.Array.insert(toobar,0,grid.customBtn);
	},
	//创建表格列属性
	createColumnMeta: function(data){
		var grid = this;
		//申明数组
		//this.columnMeta = new Array();
		this.columnHeaderMeta = new Array();
		this.columnFields = new Array();
		this.queryColumnField = {};
		// 判断是否需要显示行号
		if (this.showRowNum) {
			this.columnHeaderMeta.push(new Ext.grid.RowNumberer({
				width: 30
			}));
		}
		if(this.checked){
			var checkNum = 0;
			if(this.showRowNum){
				checkNum = 1;
			}
			//添加复选框
			var checkModel = Ext.create("Ext.selection.CheckboxModel", {
			    injectCheckbox: checkNum,//checkbox位于哪一列，默认值为0
			    mode: grid.checkMode,//multi,simple,single；默认为多选multi
			    checkOnly: grid.checkBoxOnly,//如果值为true，则只用点击checkbox列才能选中此条记录
			    allowDeselect: true,//如果值true，并且mode值为单选（single）时，可以通过点击checkbox取消对其的选择
			    enableKeyNav: true
			});
			this.selModel = checkModel;
		}
		//总列数
		var allHeaderCount = data.list;
		for(i in data.list){
			var columnData = data.list[i];
			//获取列显示名称
			var columnName = columnData.zh_cn;
			//获取列对应的映射字段
			var columnMappingName = columnData.en_us;
			//获取列的显示宽度
			var columnWidth = parseInt(columnData.show_width || this.fieldWidth);

			var mappingDisplayField = this.parseUserConfig(columnMappingName,columnData.user_config);
			var column = null;
			//判断是否可编辑
			var field = grid.createEditorCell(columnData);;
			/*if(this.gridEditor){
				var field = grid.createEditorCell(columnData);
			}*/
			//添加编辑框字段信息
			this.queryColumnField[columnMappingName] = field;
			
			if(mappingDisplayField !=null){
				/**
				 * 添加下拉树，选择节点字段
				 */
				column = {
						text : columnName,//表头显示名称
						fieldName: columnMappingName,//字段名称英文
						width : columnWidth,
						sortable : true,
						index : (i + 1) * 10,//索引序号
						dataIndex : columnMappingName+"_DISPLAYVALUE",//映射store中field字段
						isDisplayField: true,//是否是编码映转换
						hidden : false,
						editor: (this.gridEditor ? field:false)
					};
			}else{
				//动态生成列
				column = {
					text : columnName,//表头显示名称
					fieldName: columnMappingName,//字段名称英文
					width : columnWidth,
					sortable : true,
					index : (i + 1) * 10,//索引序号
					dataIndex : columnMappingName,//映射store中field字段
					isDisplayField: false,//是否是编码映转换
					hidden : false,//是否需要隐藏字段显示
					editor: (this.gridEditor ? field:false),
					allowBlank: field.allowBlank,//表示该字段是否必填false:必填,true不必填,
					required_field: true//表示需要验证字段
				};
			}
			
			if(!Ext.isEmpty(column)){
				//展示是否隐藏字段
				column = this.parseHiddenField(column);
				//处理是否需要统计
				column = this.parseStatisticsField(column);
				//添加映射数值列表
				this.columnHeaderMeta.push(column);
			}
			//存储字段列表到全局变量中
			this.columnFields.push(columnData);
		}
		//统一分配系统默认用户，组织所有人字段
		this.columnHeaderMeta.push({
			text : "创建用户编码",//表头显示名称
			fieldName: "CREATE_USER_ID",//字段名称英文
			width : this.fieldWidth,
			sortable : true,
			index : (allHeaderCount + 1) * 10,//索引序号
			dataIndex : "CREATE_USER_ID",//映射store中field字段
			//默认不显示
			hidden : true
		},{
			text : "创建用户",//表头显示名称
			fieldName: "CREATE_USER_NAME",//字段名称英文
			width : this.fieldWidth,
			sortable : true,
			index : (allHeaderCount + 2) * 10,//索引序号
			dataIndex : "CREATE_USER_NAME",//映射store中field字段
			//默认不显示
			hidden : true
		},{
			text : "创建日期",//表头显示名称
			fieldName: "CREATE_DATE",//字段名称英文
			width : this.fieldWidth,
			sortable : true,
			index : (allHeaderCount + 3) * 10,//索引序号
			dataIndex : "CREATE_DATE",//映射store中field字段
			//默认不显示
			hidden : true
		},{
			text : "更新人编码",//表头显示名称
			fieldName: "UPDATE_USER_ID",//字段名称英文
			width : this.fieldWidth,
			sortable : true,
			index : (allHeaderCount + 4) * 10,//索引序号
			dataIndex : "UPDATE_USER_ID",//映射store中field字段
			//默认不显示
			hidden : true
		},{
			text : "更新人",//表头显示名称
			fieldName: "UPDATE_USER_NAME",//字段名称英文
			width : this.fieldWidth,
			sortable : true,
			index : (allHeaderCount + 5) * 10,//索引序号
			dataIndex : "UPDATE_USER_NAME",//映射store中field字段
			//默认不显示
			hidden : true
		},{
			text : "更新日期",//表头显示名称
			fieldName: "UPDATE_DATE",//字段名称英文
			width : this.fieldWidth,
			sortable : true,
			index : (allHeaderCount + 6) * 10,//索引序号
			dataIndex : "UPDATE_DATE",//映射store中field字段
			//默认不显示
			hidden : true
		},{
			text : "信息所有人编码",//表头显示名称
			fieldName: "OWNER_USER_ID",//字段名称英文
			width : this.fieldWidth,
			sortable : true,
			index : (allHeaderCount + 7) * 10,//索引序号
			dataIndex : "OWNER_USER_ID",//映射store中field字段
			//默认不显示
			hidden : true
		},{
			text : "信息所属组织",//表头显示名称
			fieldName: "OWNER_ORG_ID",//字段名称英文
			width : this.fieldWidth,
			sortable : true,
			index : (allHeaderCount + 8) * 10,//索引序号
			dataIndex : "OWNER_ORG_ID",//映射store中field字段
			//默认不显示
			hidden : true
		},{
			text : "操作日期",//表头显示名称
			fieldName: "TIME_STAMP",//字段名称英文
			width : this.fieldWidth,
			sortable : true,
			index : (allHeaderCount + 8) * 10,//索引序号
			dataIndex : "TIME_STAMP",//映射store中field字段
			//默认不显示
			hidden : true
		});
		//添加用户自定义列
		if(Ext.typeOf(this.userConfigColumn)=="array"){
			for(j in this.userConfigColumn){
				var index = this.userConfigColumn[j].index;
				//判断序号非越界数组，插入数组到指定位置
				if(index < this.columnHeaderMeta.length){
					//Utils.insertArray(index,this.userConfigColumn[j],this.columnHeaderMeta);
					Ext.Array.insert(this.columnHeaderMeta,index,this.userConfigColumn[j]);
				}else{
					//越界直接插入到数组的最后位置
					this.columnHeaderMeta.push(this.userConfigColumn[j]);
				}
			}
		}
	},
	/**
	 * 行编辑后事件，当gridEditor=true时成效,注入回调参数grid：表格，record：记录,column:列
	 * function(grid,record,column){}
	 */
	afterRowEditor: Ext.emptyFn,
	/**
	 * 添加可编辑插件
	 */
	addEditorPlugins: function(){
		var grid = this;
		//判断是否可编辑
		if(this.gridEditor){
			var plugins = Ext.create('Ext.grid.plugin.CellEditing', {
				pluginId:'rowEditing',//必须定义可以通过该名称找到plugins
		        clicksToEdit : 1,
		        listeners : {
		            beforeedit : function(editor, e, eOpts) {
		                return true;
		            },
		            edit : function(editor, e) {
		            	//debugger;
		            	//alert(e.record.getId());
		            	var id = e.column.getEditor().fieldId;
		            	//id = id.substr(id.indexOf("_")+1);
		            	var name = e.column.getEditor().getName();
		            	var xtype = e.column.getEditor().getXType();
		            	if(xtype=="select"){
		            		e.record.set(id+"_DISPLAYVALUE", e.column.getEditor().getDisplayValue());
			                e.record.set(id, e.column.getEditor().getValue());
		            	}else if(xtype=="tree"){
		            		e.record.set(id+"_DISPLAYVALUE", e.column.getEditor().getRawValue());
			                e.record.set(id, e.column.getEditor().getValue());
		            	}else if(xtype=="datefield"){
		    				e.record.set(id,e.column.getEditor().getRawValue());
		            	}else{
		            		e.record.set(id, e.column.getEditor().getValue());
		            	}
		            	//debugger;
		                //设置记录状态为修改
		            	if(Ext.isEmpty(e.record.getId())){
		            		e.record.state = Constants.RECORD_NEW;
		            	}else{
		            		e.record.state = Constants.RECORD_CHANGED;
		            	}
		            	//debugger;
		            	//判断是否存在行编辑后事件，存在需要调用
		            	if(editor.grid.afterRowEditor !=Ext.emptyFn){
							Ext.callback(editor.grid.afterRowEditor,this,[grid,e.record,e.column]);
						}
		            	

		            }/*,
		            validateedit: function(editor, e, eOpts){
		            	debugger;
		            }*/
		        }
		    });
			//this.plugins = plugins;
			this.addPlugin(plugins);
		}
	},
	/***
	 * 创建可编辑单元格
	 * 用于用户设置单元格可编辑时操作,返回具体的操作字段
	 */
	createEditorCell: function(metaField){
		var form = this;
		var field = null;
		var allowBlank = true;
		if(metaField.is_primary_key == Constants.YES){
			//必填
			allowBlank = false;
		}else if(metaField.is_empty == Constants.NO){
			//必填
			allowBlank = false;
		}else{
			//非必填
			allowBlank = true;
		}
		//防止可编辑框的表单id和其他表单重复，默认加上当前的grid编码，获取数据时也需要带上该编码
		
		var fieldId = metaField.en_us;
		//alert(fieldId+":"+allowBlank);
		if(Ext.isEmpty(metaField.user_config)){
			field = Ext.create('Ext.form.field.Text',{
				fieldId: fieldId,
				allowBlank: allowBlank
			});
		}else{
			var config = Ext.JSON.decode(metaField.user_config);
			var ftype = config.ftype;
			var required = config.required || false;
			if(required){
				//必填
				allowBlank = false;
			}
			//alert(fieldId+":"+allowBlank);
			switch(ftype){
				case Constants.FIELDSELECT:{
						//判断该字段是否有动态关联字段
						var linkage = config.linkage || false;
						//动态关联字段
						var linkagefield = config.linkagefield || "";
						//动态关联字段的查询字段
						var linkagefilterfield = config.linkagefilterfield || "";

						field = Ext.create("Ext.com.bkfm.combobox",{
							fieldId: fieldId,
							allowBlank: allowBlank,
							editable: true,
							objPath: metaField.obj_path,
							loadingText:'加载中……'
						});
					break;
				}
				case Constants.FIELDDATE:{
					field = Ext.create('Ext.form.field.Date',{
						fieldId: fieldId,
						allowBlank: allowBlank,
						format: config.format || 'Y-m-d'
					});
					break;
				}
				case Constants.FIELDNUMBER:{
					field = Ext.create('Ext.form.field.Number',{
						fieldId: fieldId,
						allowBlank: allowBlank,
						hideTrigger: true,
				        keyNavEnabled: false,
				        mouseWheelEnabled: false
					});
					break;
				}
				case Constants.FIELDPASSWORD:{
					field = Ext.create('Ext.form.field.Text',{
						fieldId: fieldId,
						allowBlank: allowBlank,
						inputType: 'password'
					});
					break;
				}
				case Constants.FIELDCHECKBOX:{
					field = Ext.create('Ext.form.field.Checkbox',{
						fieldId: fieldId,
						allowBlank: allowBlank
					});
					break;
				}
				case Constants.FIELDTREE:{
					 field = Ext.create("Ext.com.bkfm.comboboxtree", {
						 	fieldId: fieldId,
					        //cascade : 'parent',//级联方式:1.child子级联;2.parent,父级联,3,both全部级联
					        checkModel:'single',//当json数据为不带checked的数据时只配置为single,带checked配置为double为单选,不配置为多选
					        treeConfigId: config.treeConfigId,
					        rootId: config.rootTreeId,
					        treeNodeParameter : {

					        }
					    });
					break;
				}
				default:{
					field = Ext.create('Ext.form.field.Text',{
						id: fieldId,
						allowBlank: allowBlank
					});
					break;
				}
			}
		}
		return field;
	},
	/**
	 * grid数据加载之前执行函数
	 */
	beforeload: Ext.emptyFn,
	/**
	 * 数据加载之后执行函数
	 */
	afterload: Ext.emptyFn,
	//获取表格数据
	getGridStoreData : function() {
		var grid = this;
		var proxy_url = CONTEXT.contextPath + "/bkfm/metadata/v1/querytablemetacolumndatalist";
		//定义Ext.data.Model fields数组
		var fields = new Array();
		//alert("长度"+fields.length);
		for(i in this.columnFields){
			var meta = this.columnFields[i];
			var field_model_config = this.createDataModel(meta);
			fields.push(field_model_config);
			//判断是否为下拉的键值对应关系，如果是则添加键值转换列
			var mappingDisplayField = this.parseUserConfig(meta.en_us,meta.user_config);
			if(mappingDisplayField !=null){
				fields.push(mappingDisplayField);
			}
		}
		
		//添加默认表字段
		fields.push({
			name: "CREATE_USER_ID",
			mapping: "CREATE_USER_ID"
		},{
			name: "CREATE_USER_NAME",
			mapping: "CREATE_USER_NAME"
		},{
			name: "CREATE_DATE",
			mapping: "CREATE_DATE"
		},{
			name: "UPDATE_USER_ID",
			mapping: "UPDATE_USER_ID"
		},{
			name: "UPDATE_USER_NAME",
			mapping: "UPDATE_USER_NAME"
		},{
			name: "UPDATE_DATE",
			mapping: "UPDATE_DATE"
		},{
			name: "OWNER_USER_ID",
			mapping: "OWNER_USER_ID"
		},{
			name: "OWNER_ORG_ID",
			mapping: "OWNER_ORG_ID"
		},{
			name: "TIME_STAMP",
			mapping: "TIME_STAMP"
		});

		//定义Ext.data.Model id名称
		var modelId = this.id+"_data_model";
		//alert(modelId);
		//定义grid的model列
		this.modelField = Ext.define(modelId, {
	        extend: 'Ext.data.Model',
	        fields: fields
	    });

		// 定义构造器
		var _proxy = new Ext.data.HttpProxy({
					url : proxy_url,
					type: 'ajax',
					//设置为post提交，默认为get提交
		            getMethod: function(){
		            	return 'post';
		            },
					reader: {
						type: 'json',
						idProperty: 'RWID',
		                root: 'list',
		                totalProperty: 'total',
		                listeners:{
		                	exception: function(reader,response,error,eOpts){
		                		//当reader从服务端接收到不正确的编码数据时触发
		                		Utils.log(error);
		                	}
		                }
		            }

				});
		//定义store
        var store = Ext.create('Ext.data.Store', {
            model: modelId,
            proxy : _proxy,
            pageSize: grid.pageSize,
            autoLoad: grid.loadAuto,
            baseParams:{
            	obj_path : grid.objPath, // 建模对象
            	filter : grid.filter,
            	orderby: grid.orderby,
				limit: grid.pageSize,
				paging: grid.paging//是否分页
            },
			listeners : {
				beforeload : function(store,operation,eOpts) {
					AjaxUtils.showProgress();
					if(grid.beforeload != Ext.emptyFn){
						Ext.callback(grid.beforeload,this,[store,operation]);
					}
					//设置查询分页开始记录参数
					//debugger;
					//this.baseParams.offset = operation.page;
					/*debugger;
					if(Ext.isEmpty(operation.params)){
						//alert(0);
						operation['params'] = {};
						Ext.apply(operation.params,this.baseParams);
						//operation.params = this.baseParams;
						operation.params['offset'] = operation.page;
					}else{
						//alert(2);
						operation.params['offset'] = operation.params.page;
						operation['page'] = operation.params.page;
						operation['start'] = operation.params.start;
					}
					Ext.apply(store.proxy.extraParams, operation.params);*/
					if(Ext.isEmpty(operation.params)){
						operation.params = this.baseParams;
						operation.params['offset'] = operation.page;
					}else{
						if(operation.params.Re_Search){
							//重新查询
							operation.params['offset'] = 1;
							operation.params['page'] = 1;
						}else{
							operation.params['offset'] = operation.page;
						}
						operation.params['offset'] = operation.params.page;
						operation['page'] = operation.params.page;
						operation['start'] = operation.params.start;
						Ext.apply(operation.params,this.baseParams);
					}
					Ext.apply(store.proxy.extraParams, operation.params);
				},
				load : function(store,records,successful,eOpts) {
					AjaxUtils.closeProgress();
					if(grid.afterload != Ext.emptyFn){
						Ext.callback(grid.afterload,this,[store,records]);
					}
				}
			}
        });
		return store;
	},
	//创建分页工具栏
	paddingInfo: function(){
		if(this.paging){
			var grid = this;
			//alert(grid.getId());
			var pager = Ext.create('Ext.PagingToolbar', {
				id: grid.getId()+"_paging",
	            pageSize: grid.pageSize,
	            store: grid.store,
	            displayInfo: true,
	            beforePageText: '第',
				afterPageText : "页,共{0}页",
				firstText : "第1页",
				prevText : "上一页",
				nextText : "下一页",
				lastText : "最后一页",
				refreshText : "刷新",
	            displayMsg: '<div id="'+grid.getId()+'_pageInfo">显示第 <font color=red>{0}</font> 条到 <font color=red>{1}</font> 条记录，一共<font color=red> {2}</font> 条</div>',
	            emptyMsg: "暂无数据",
	            listeners:{
	            	beforechange: function(paging,page,eOpts ){
	            		//debugger;
	            	},
	            	change: function(paging,pageData,eOpts){
	            		if(!Ext.isEmpty(pageData)){
		            		if(pageData.currentPage > pageData.pageCount){
		            			pageData.currentPage = 1;//第一页
		            			pageData.fromRecord=1;//第一条
		            			pageData.toRecord = grid.pageSize;//设置的显示记录条
		            			//获取分页工具栏
		            			var pag_toolbar = grid.getDockedItems('toolbar[dock="bottom"]')[0];
		            			//inputItem
		            			var numberfield = Ext.getCmp(grid.getId()+"_paging").query("numberfield")[0];
		            			numberfield.setValue(1);
			            		var displayMsg = "显示第 <font color=red>{0}</font> 条到 <font color=red>{1}</font> 条记录，一共<font color=red> {2}</font> 条";
			            		var msg = Ext.String.format(displayMsg,pageData.fromRecord,pageData.toRecord,pageData.total);
			            		Ext.get(grid.getId()+"_pageInfo").setHTML(msg);
		            			Ext.getCmp(grid.getId()+"_paging").moveFirst();
		            		}
	            		}

	            	}
	            }
	        });
	        //this.pageToolBar = pager ;
			this.bbar = pager ;
		}
	},
	//创建store的字段类型
	createDataModel: function(meta){
		var fieldConfig = {
				name: meta.en_us,
				mapping: meta.en_us
		};
		var userConfig = Ext.JSON.decode(meta.user_config || "{}");
		
		switch(meta.model_field){
			case '1':{
				fieldConfig.type = "string";
				//字符串日期
				if(userConfig.ftype=="date"){
					fieldConfig.convert = function(value){
						if(Ext.isEmpty(value)){
							return "";
						}else{
							//debugger;
							var date = new Date(Date.parse(value.replace(/-/g, "/")));
							var createTime = Ext.Date.format(date,userConfig.format || "Y-m-d");
							return createTime;
						}

			         } ;
				}
				break;
			}
			case '2':{
				fieldConfig.type = "number";
				break;
			}
			case '3':{
				fieldConfig.type = "date";
				//日期格式化为年月日，时分秒
				fieldConfig.convert = function(value){
					if(Ext.isEmpty(value)){
						return "";
					}else{
						var date = new Date(Date.parse(value.replace(/-/g, "/")));
						var createTime = Ext.Date.format(date,userConfig.format || "Y-m-d");
						return createTime;
					}

		         } ;
				break;
			}
			case '4':{
				fieldConfig.type = "float";
				break;
			}
			default:{
				fieldConfig.type = "string";
				break;
			}
		}
		return fieldConfig;
	},
	//处理用户自定义配置信息,解析用户字段为下拉配置时的映射关系
	parseUserConfig: function(enname,userConfig){
		if(Ext.isEmpty(userConfig)){
			return null;
		}
		var config = Ext.JSON.decode(userConfig);
		var ftype = config.ftype;
		
		if(ftype==Constants.FIELDSELECT || ftype==Constants.FIELDTREE){
			var fieldConfig = {
					name: enname+"_DISPLAYVALUE",
					mapping: enname+"_DISPLAYVALUE",
					type: 'string'
			};
			return fieldConfig;
		}

		return null;

	},
	/**
	 * 转换表格字段，设置表格的每一列是否需要隐藏
	 * field: 表格列
	 */
	parseHiddenField: function(field){
		var name = field.fieldName;
		if(!Ext.isEmpty(this.hiddenField)){
			if(Ext.Array.contains(this.hiddenField,name)){
				field.hidden = true;
			}
		}
		return field;
	},
	/**
	 * 是否进行字段值统计
	 */
	parseStatisticsField: function(field){
		if(this.statistics && !Ext.isEmpty(this.statisticsField)){
			//获取字段名
			var field_name = field.fieldName;
			if(this.statisticsField.hasOwnProperty(field_name)){
				var field_static_config = this.statisticsField[field_name];
				if(!Ext.isEmpty(field_static_config)){
					field.summaryType = field_static_config["summaryType"] || null;
					if(Ext.isFunction(field_static_config["summaryRenderer"])){
						field.summaryRenderer = field_static_config["summaryRenderer"];
					}
				}
			}
		}
		return field;
	},
	/**
	 * 根据记录id选中记录行
	 */
	selectRecordById: function(id){
		var record = this.getStore().getById(id);
		if(record){
			this.getSelectionModel().select(record.index,true);
		}
	},
	/**
	 * 根据记录索引行号选中记录行
	 */
	selectRecordByIndex: function(index){
		this.getSelectionModel().select(index,true);
	},
	/**
	 * 选择一条记录
	 */
	getSelectedRecord: function(){
		var records = this.getSelectedRecords();
		if(records.length !=1){
			AjaxUtils.showError("请选择一条记录");
			return null;
		}
		return records[0];
	},
	/**
	 * 获取表格没有选中的数据
	 */
	getUnSelectRecords: function(){
		var records = this.getSelectedRecords();
		//获取选中行的索引号
		var selIndex = [];
		Ext.Array.each(records,function(record,index){
			selIndex.push(record.id);
		});
		var allRecords = this.getStore().getRange();
		var unSelectRecords = [];
		Ext.Array.each(allRecords,function(record,index){
			var record_index = record.id;
			if(!Ext.Array.contains(selIndex,record_index)){
				unSelectRecords.push(record);
			}
		});
		return unSelectRecords;
	},
	//获取当前选中记录
	getSelectedRecords: function(){
		var records = this.getSelectionModel().getSelection();
		return records;
	},
	//获取选中记录id
	getRecordId: function(record){
		if(record){
			return record.getId();
		}
		AjaxUtils.showError('无效的记录参数值');
		return "";
	},
	/**
	 * 获取grid修改的数据
	 */
	getModifiedRecords: function(){
		if(this.gridEditor){
			return this.getStore().getModifiedRecords();
		}else{
			console.log("当前grid不可编辑，无法获取修改数据记录");
			return null;
		}

	},
	/**
	 * 根据字段名称获取表格列，
	 * 返回执行名称所在的列
	 */
	getColumnByFieldName: function(fieldName){
		var columns = this.getColumns();
		var column = null;
		Ext.Array.each(columns,function(col,index){
			if(col.fieldName && col.fieldName == fieldName){
				column = col;
				return false;
			}
		});
		return column;
	},
	/**
	 * 获取表格列属性
	 */
	getColumns: function(){
		return this.columns;
	},
	/**
	 * 设置全局查询条件
	 */
	/*setFilter: function(filter){
		this.filter = filter;
		this.getStore().baseParams.filter = this.filter;
		Ext.apply(this.getStore().proxy.extraParams, this.getStore().baseParams);
	},*/
	/**
	 * 获取全局查询条件
	 */
	getFilter: function(){
		return this.filter;
	},
	/**
	 * 保存修改的数据
	 * callback 回调函数
	 */
	save: function(callback){
		if(!this.gridEditor){
			AjaxUtils.showError('非可编辑表格，无效的操作权限');
			return;
		}
		var records = this.getModifiedRecords();
		if(!records || records.length ==0){
			AjaxUtils.showError('无修改数据记录');
			return;
		}

		var savePath = this.objPath;
		if(!Ext.isEmpty(this.saveObjPath)){
			savePath = this.saveObjPath;
		}

		var grid = this;
		var submitRecord = new Array();
		var isvalid = true;
		Ext.each(records, function(item, rowindex) {
			var rwid = item.getId();
			if(Ext.isEmpty(rwid) || item.state == Constants.RECORD_NEW){
				//新纪录或者rwid为空
				rwid = Utils.getRwid();
			}
			submitRecord.push({
				"obj_path": savePath,
				"record_state": item.state,
				"rwid": rwid,
				"record_data": Ext.JSON.encode(item.data)
			});
			for(i in grid.columnHeaderMeta){
				var col = grid.columnHeaderMeta[i];
				if(col.required_field){
					var col_name = col.fieldName;
					var col_dis_name = col.text;
					if(!col.allowBlank && Ext.isEmpty(item.data[col_name])){
						AjaxUtils.showError('表单第'+(rowindex+1)+'行，【'+col_dis_name+'】,不可为空');
						isvalid = false;
						return false;
					}
				}
			}
		});
		if(!isvalid){
			return ;
		}
		AjaxUtils.CallService({
			url: CONTEXT.contextPath+"/bkfm/metadata/v1/savemodelmetadata",
			dataType: "json",
			params: submitRecord,
			call: function(data){
				if(Ext.isFunction(callback)){
					callback(data);
				}else{
					if(data.status == "OK"){
						grid.reload();
					}else{
						AjaxUtils.showError('操作失败');
					}
				}

			}
		});

	},
	/**
	 * 新建一条空记录
	 * @callback 回调函数，参数为新建的行记录
	 */
	addNewRecord: function(callback){
		if(!this.gridEditor){
			AjaxUtils.showError('非可编辑表格，无效的操作权限');
			return;
		}
		var record = Ext.create(this.modelField,{});
		//设置记录状态为新增
		record.state = Constants.RECORD_NEW;
		this.getStore().insert(0,record);
		if(this.gridEditor){
			//如果表格为可编辑状态，则默认设置当前行记录为可编辑
			var rowEditing = this.getPlugin("rowEditing");
			rowEditing.startEdit(0,0);
		}
		if(Ext.isFunction(callback)){
			callback(record);
		}
	},
	/**
	 * 删除记录后执行的操作动作，仅有当deleteRecords函数中的callback回调函数不存在时生效
	 * 注入：result：执行结果
	 * del_rwid：删除数据的rwid
	 */
	afterDeleteRecords: Ext.emptyFn,
	/**
	 * 删除选择记录
	 * @param {} callback 回调函数
	 */
	deleteRecords: function(callback){
		var records = this.getSelectedRecords();
		if(Ext.isEmpty(records)){
			return;
		}
		var grid = this;
		var del_rwid = new Array();
		var del_param = new Array();
		for(i in records){
			var r = records[i];
			if(r.getId()){
				del_param.push({
					"obj_path": grid.objPath,
					"rwid": r.getId()
				});
				del_rwid.push(r.getId());
			}else{
				this.getStore().remove(r);
			}

		}
		//判断是否需要远程删除
		if(Ext.isEmpty(del_param)){
			return;
		}
		var grid = this;
		AjaxUtils.showConfirm(function(){
			AjaxUtils.CallService({
				url: CONTEXT.contextPath+"/bkfm/metadata/v1/delmodelmetadata",
				dataType: "json",
				params: del_param,
				call: function(result){
					if(Ext.isFunction(callback) && grid.afterDeleteRecords != Ext.emptyFn){
						/**
						 * 后台状态，删除的表格记录id集合
						 */
						callback(result,del_rwid);
					}else if(grid.afterDeleteRecords != Ext.emptyFn){
							Ext.callback(grid.afterDeleteRecords,this,[result,del_rwid]);
					}else{
						grid.reload();
					}

				}
			});			
		},"确定需要删除选中的记录？删除后将不可恢复!");
	},
	/**
	 * 导入查询结果
	 */
	importGridData: function(){
		var selfGrid = this;
		var imp_grid_id = selfGrid.getId()+'_impgrid';
		var imp_form_id = selfGrid.getId()+'_impform';
		
		// 自定义数据模型
		var myModel = Ext.define("dateImpInfo", {
			extend : 'Ext.data.Model',
			fields : [ {
				name : 'field_label',
				type : 'string'
			}, {
				name : 'field_name',
				type : 'string'
			},{
				name: 'field_excel_head',
				type: 'string'
			},{
				name: 'field_excel_head_col',
				type: 'int'
			}]
		});
		var exp_column_data = new Array(); 
		var myStore = Ext.create("Ext.data.Store", {
			model : 'dateImpInfo',
			data : exp_column_data
		});
		
		
		var win = Ext.create('Ext.com.bkfm.window', {
			title : '数据导入',
			autoScroll : true,
			modal : true,
			height : Utils.getHeight() - 100,
			width : Utils.getWidth() - 100,
			layout: 'card',
			items:[{
				xtype: 'form',
				id: imp_form_id,
				title: '【第一步】选择需要导入的文件',
				tbar:[{
					text: '下一步',
					iconCls: 'next',
					handler: function(){
						var form = Ext.getCmp(imp_form_id);
						var uploadField = form.down('#upload_file');
						if(!uploadField.isValid()){
							AjaxUtils.showError('请选择需要导入Excel的文件');
							return;
						}
						form.submit({
							url:CONTEXT.contextPath+'/bkfm/common/v1/loadimpexcelcol',
							params: {
								obj_path: selfGrid.objPath
						    },
							waitMsg:'文件上传中',//提示等待信息
							success:function(form, action){
								win.getLayout().setActiveItem(1);
								var impgrid = Ext.getCmp(imp_grid_id);
								var exp_column_data = action.result.result.entity.imp_field;
								var file_id = action.result.result.entity.file_id;
								impgrid.file_id=file_id;
								impgrid.getStore().loadData(exp_column_data);
								impgrid.getSelectionModel().selectAll();
							},
							failure: function(form, action) {
							   AjaxUtils.showError('导入文件上传失败,请确认上传文件类型是否合法');
							}
						});
					}
				}],
				items:[{
					xtype:'filefield',
					style: {
			            width: '50%',
			            margin: '150px;'
			        },
			        id: 'upload_file',
					name:'upload_file',
					fieldLabel:'导入文件',
					labelWidth:100,
					msgTarget:'side',
					allowBlank:false,
					anchor:'98%',
					buttonText:'请选择文件',
					regex: /^.+\.(xls|xlsx)$/,
					regexText: "只能选择xls|xlsx格式的文件"
				}]
			},{
				xtype: 'grid',
				id: imp_grid_id,
				title: '【第二步】配置导入数据列',
				tbar:[{
					text: '上一步',
					iconCls: 'previous',
					handler: function(){
						win.getLayout().setActiveItem(0);
					}
				},{
					text: '确定导入',
					iconCls: 'ok',
					handler: function(){
						var impgrid = Ext.getCmp(imp_grid_id);
						if(impgrid.getSelectionModel().getSelection().length==0){
							AjaxUtils.showError('请选择需要导入的字段信息');
							return;
						}
						win.getLayout().setActiveItem(2);
						Ext.getDom("impImp").src=CONTEXT.contextPath+'/assets/images/wating.gif';
						Ext.getDom("impInfo").innerHTML='正在导入请稍候......!';
						AjaxUtils.showConfirm(function(){
							var imp_field_records = impgrid.getSelectionModel().getSelection();
							var field_list = new Array();
							for(i in imp_field_records){
								var field = imp_field_records[i];
								field_list.push({
									"field_label": field.get("field_label"),
									"field_name": field.get("field_name"),
									"field_excel_head": field.get("field_excel_head"),
									"field_excel_head_col": field.get("field_excel_head_col")
								});
							}
							AjaxUtils.CallService({
								url: CONTEXT.contextPath+"/bkfm/common/v1/import?file_id="+impgrid.file_id+"&obj_path="+selfGrid.objPath,
								dataType: "json",
								params: field_list,
								call: function(result){
									if(result.status == "OK"){
										Ext.getDom("impImp").src=CONTEXT.contextPath+'/assets/images/gou.jpg';
										Ext.getDom("impInfo").innerHTML='<a href="javascript:void(0)" target="_blank" style="color:red;text-decoration:none;">数据导入成功</a>';
										/*AjaxUtils.showInfo('数据导入成功',function(){
											selfGrid.reload();
										});*/
										selfGrid.reload();
									}else{
										Ext.getDom("impImp").src=CONTEXT.contextPath+'/assets/images/cha.jpg';
										Ext.getDom("impInfo").innerHTML='<a href="javascript:void(0);" target="_blank" style="color:red;text-decoration:none;">数据导入失败</a>';
									}
								}
							});			
						},"确定需要导入选中的数据列?");
					}
				}],
				selModel:Ext.create("Ext.selection.CheckboxModel", {
				    injectCheckbox: 1,//checkbox位于哪一列，默认值为0
				    mode: 'multi',//multi,simple,single；默认为多选multi
				    checkOnly: false,//如果值为true，则只用点击checkbox列才能选中此条记录
				    allowDeselect: true,//如果值true，并且mode值为单选（single）时，可以通过点击checkbox取消对其的选择
				    enableKeyNav: true
				}),
				columns : [ {
					xtype : 'rownumberer',
					text : ''
				}, {
					text : '导入信息',
					dataIndex : 'field_label',
					width:200
				}, {
					text : '导入字段',
					dataIndex : 'field_name',
					width:200,
					hidden:false
				}, {
					text : 'Excel映射字段',
					dataIndex : 'field_excel_head',
					width:200,
					hidden:false
				}, {
					text : 'Excel映射列',
					dataIndex : 'field_excel_head_col',
					width:200,
					hidden:false
				}],
				store : myStore
			},{
				xtype: 'panel',
				tbar:[{
					text: '上一步',
					iconCls: 'previous',
					handler: function(){
						win.getLayout().setActiveItem(1);
					}
				}],
				title: '【第三步】导入数据',
				html: '<div id="exp_info" style="padding-top:200px;width:100%;height:100%;text-align:center;"><img id="impImp" src="'+CONTEXT.contextPath+'/assets/images/wating.gif" width="100" height="100"/><h1 id="impInfo">正在导入请稍候......!</h1></div>'
			}]
		});
		win.show(this,function(){
			win.getLayout().setActiveItem(0);
		});
	},
	/**
	 * excel文件导出
	 */
	exportGridDate: function(){
		var selfGrid = this;
		// 自定义数据模型
		var myModel = Ext.define("dateInfo", {
			extend : 'Ext.data.Model',
			fields : [ {
				name : 'field_label',
				type : 'string'
			}, {
				name : 'field_name',
				type : 'string'
			}]
		});
 
		var exp_column_data = new Array();
	    for(i in this.columnHeaderMeta){
	    	var field = this.columnHeaderMeta[i];
	    	if(!field.fieldName){
	    		continue;
	    	}
	    	//debugger;
	    	if(field.isDisplayField){
	    		
		    	exp_column_data.push({
		    		"field_label": field.text+"_编码",
		    		"field_name": field.fieldName
		    	});
		    	exp_column_data.push({
		    		"field_label": field.text,
		    		"field_name": field.fieldName+"_DISPLAYVALUE"
		    	});
	    	}else{
		    	exp_column_data.push({
		    		"field_label": field.text,
		    		"field_name": field.fieldName
		    	});	    		
	    	}

	    }
		var myStore = Ext.create("Ext.data.Store", {
			model : 'dateInfo',
			data : exp_column_data
		});
		var exp_grid_id = selfGrid.getId()+'_expgrid';
		var win = Ext.create('Ext.com.bkfm.window', {
			title : '数据导出',
			autoScroll : true,
			modal : true,
			height : Utils.getHeight() - 100,
			width : Utils.getWidth() - 100,
			layout: 'card',
			items:[{
				xtype: 'grid',
				id: exp_grid_id,
				height: 200,
				title: '【第一步】导出列选择',
				selModel:Ext.create("Ext.selection.CheckboxModel", {
				    injectCheckbox: 1,//checkbox位于哪一列，默认值为0
				    mode: 'multi',//multi,simple,single；默认为多选multi
				    checkOnly: false,//如果值为true，则只用点击checkbox列才能选中此条记录
				    allowDeselect: true,//如果值true，并且mode值为单选（single）时，可以通过点击checkbox取消对其的选择
				    enableKeyNav: true
				}),
				tbar:[{
					text: '下一步',
					iconCls: 'next',
					handler: function(){
						var expFieldRecord = Ext.getCmp(exp_grid_id).getSelectionModel().getSelection();
						if(expFieldRecord.length ==0){
							AjaxUtils.showError('请选择需要导出的字段');
							return;
						}
						win.getLayout().setActiveItem(1);
						var columns = [];
						for(i in expFieldRecord){
							var record = expFieldRecord[i];
							columns.push(record.get("field_name"));
						}
						Ext.getDom("expImp").src=CONTEXT.contextPath+'/assets/images/wating.gif';
						Ext.getDom("expInfo").innerHTML='正在导出请稍候......!';
						AjaxUtils.CallService({
							url: CONTEXT.contextPath+"/bkfm/common/v1/export",
							params: {
								filter: selfGrid.getStore().baseParams.filter,
								obj_path: selfGrid.getStore().baseParams.obj_path,
								orderby: selfGrid.getStore().baseParams.orderby,
								expColumn: columns.join(",")
							},
							call: function(result){
								if(result.status == "OK"){
									var path = result.entity;
									Ext.getDom("expImp").src=CONTEXT.contextPath+'/assets/images/gou.jpg';
									Ext.getDom("expInfo").innerHTML='<a href="'+CONTEXT.contextPath+'/bkfm/common/download?downloadInfo='+encodeURIComponent(path)+'" target="_blank" style="color:red;text-decoration:none;">文件已经生成，点击下载</a>';
								}else{
									Ext.getDom("expImp").src=CONTEXT.contextPath+'/assets/images/cha.jpg';
									Ext.getDom("expInfo").innerHTML='<a href="javascript:void(0);" target="_blank" style="color:red;text-decoration:none;">下载文件失败</a>';
								}
							}
						});
					}
				}],
				columns : [ {
					xtype : 'rownumberer',
					text : ''
				}, {
					text : '导出信息',
					dataIndex : 'field_label',
					width:200
				}, {
					text : '导出字段',
					dataIndex : 'field_name',
					width:200,
					hidden:false
				}],
				store : myStore
			},{
				xtype: 'panel',
				title: '【第二步】导出数据',
				tbar:[{
					text: '上一步',
					iconCls: 'previous',
					handler: function(){
						win.getLayout().setActiveItem(0);
					}
				}],
				html: '<div id="exp_info" style="padding-top:200px;width:100%;height:100%;text-align:center;"><img id="expImp" src="'+CONTEXT.contextPath+'/assets/images/wating.gif" width="100" height="100"/><h1 id="expInfo">正在导出请稍候......!</h1></div>'
			}]
			
		});
		win.show(this,function(){
			win.getLayout().setActiveItem(0);
			Ext.getCmp(exp_grid_id).getSelectionModel().selectAll();
		});
		
	},
	/**
	 * 刷新grid列表
	 */
	reload: function(){
		this.getStore().load();
	},
	/**
	 * 重新查询
	 * 在原有的查询条件下再次追加条件进行查询
	 * @paramsFilter 查询条件sql语句,paramsFilter条件不需要 AND 开始
	 */
	search: function(paramsFilter){
		var grid = this;
		if(Ext.isEmpty(paramsFilter)){
			this.getStore().load({
				params : {
					appendFilter: "",
					start: 0, 
					limit: grid.pageSize,
					page: 1
				}
			});
		}else{
			//获取查询条件是否开始包含了and关键字
			var paramsFilter_case = Ext.util.Format.trim(paramsFilter).substring(0,3);
			if(Ext.util.Format.uppercase(paramsFilter_case) == "AND"){
				paramsFilter = Ext.util.Format.trim(paramsFilter).substring(3);
			}
			
			this.getStore().load({
				params : {
					appendFilter: paramsFilter,
					start: 0, 
					limit: grid.pageSize,
					page: 1
				}
			});
		}
	},
	/**
	 * 编辑表单窗体打开或者加载完成数据后回调函数
	 * 函数方法注入formTabPanel，表示打开的编辑窗体。返回tabpanel窗体
	 */
	afterFormShow: Ext.emptyFn,
	/**
	 * 窗体保存按钮执行之前操作
	 * 函数方法注入formTabPanel，表示打开的编辑窗体。返回tabpanel窗体
	 */
	beforeFormSave: Ext.emptyFn,
	/**
	 * 窗体主表单保存成功后执行
	 * 函数方法注入formTabPanel，表示打开的编辑窗体。返回tabpanel窗体,win:当前窗体
	 */
	afterFormSave: Ext.emptyFn,
	/**
	 * 打开编辑按钮
	 * edit_type: 编辑类型：add，edit，view
	 */
	showEditorForm: function(edit_type,record){
		var text_only = false;
		var title = "编辑";
		var bar_button = new Array();
		if(edit_type == "add"){
			title = "新建";
			bar_button.push({
				text : '保存',
				iconCls : 'save',
				handler : function() {
					var formTabPanel = grid.getEditPanel();
					if(grid.beforeFormSave != Ext.emptyFn){ 
						var execute = Ext.callback(grid.beforeFormSave,this,[grid,formTabPanel]);
						if(Ext.isEmpty(execute)){
							AjaxUtils.showError("执行函数“beforeFormSave”，没有返回值！");
							return ;
						}
						if(!execute){
							return;
						}
					}
					form.save(function(){
						grid.reload();
						if(grid.afterFormSave !=Ext.emptyFn){
							Ext.callback(grid.afterFormSave,this,[grid,formTabPanel,win]);
						}else{
							win.close();
						}
					});

				}
			},'-',{
				text: '关闭',
				iconCls: 'close',
				handler: function(){
					AjaxUtils.showConfirm(function(){
						win.close();
					},"确定需要关闭当前窗体？");
				}
			});
		}else if(edit_type == "edit"){
			title = "修改";
			bar_button.push({
				text : '保存',
				iconCls : 'save',
				handler : function() {debugger;
					var formTabPanel = grid.getEditPanel();
					if(grid.beforeFormSave != Ext.emptyFn){
						var execute = Ext.callback(grid.beforeFormSave,this,[grid,formTabPanel]);
						if(Ext.isEmpty(execute)){
							AjaxUtils.showError("执行函数“beforeFormSave”，没有返回值！");
							return ;
						}
						if(!execute){
							return;
						}
					}
					form.save(function(){
						grid.reload();
						if(grid.afterFormSave !=Ext.emptyFn){
							Ext.callback(grid.afterFormSave,this,[grid,formTabPanel,win]);
						}else{
							win.close();
						}
					});

				}
			},'-',{
				text: '关闭',
				iconCls: 'close',
				handler: function(){
					AjaxUtils.showConfirm(function(){
						win.close();
					},"确定需要关闭当前窗体？");
				}
			});
		}else if(edit_type == "view"){
			//之都
			text_only = true;
			title = "预览";
			bar_button.push('-',{
				text: '关闭',
				iconCls: 'close',
				handler: function(){
					AjaxUtils.showConfirm(function(){
						win.close();
					},"确定需要关闭当前窗体？");
				}
			});
		}
		var grid = this;
		var form = Ext.create('Ext.com.bkfm.form', {
			title: "基础信息",
			showGroup : false,
			//columnCount: 1,
			border : false,
			frameborder : false,
			objPath : grid.objPath,
			saveObjPath: grid.saveObjPath,
			textOnly: text_only,
			unViewField: grid.formUnViewField,
			tbar : bar_button
		});
		var win = Ext.create('Ext.com.bkfm.window', {
			title : title,
			autoScroll : true,
			modal : true,
			height : Utils.getHeight()*0.9,
			width : Utils.getWidth()*0.8,
			items: [{
				xtype: "tabpanel",
				id: grid.getId()+"_panel",
				layout: "fit",
				border: 0,
				frame: false,
				items:[form]
			}],
			listeners:{
				afterrender: function(){
					var formTabPanel = grid.getEditPanel();
					if(edit_type != "add"){
						form.loadRemoteData(record.get("id"),function(){
							Ext.callback(grid.afterFormShow,this,[grid,formTabPanel]);
							
						});
						return;
					}
					Ext.callback(grid.afterFormShow,this,[grid,formTabPanel]);
				}
			}
		});
		win.show();
	},
	/**
	 * 获取grid的新增，修改，预览的表单容器主界面
	 */
	getEditPanel: function(){
		return Ext.getCmp(this.getId()+"_panel");
	},
	/**
	 * 打开自定义查询窗体
	 */
	customizeQuery: function(){
		var super_grid = this;
		if(this.query_win){
			this.query_win.show();
			return;
		}
		
	    Ext.define('State', {  
	        extend: 'Ext.data.Model',  
	        fields: [  
	            {name: 'value' },  
	            {name: 'text' }  
	        ]  
	    });  
	    //查询规则
	    var rule_combo = Ext.create('Ext.form.field.ComboBox', {
	    	displayField: 'text',
	        valueField: 'value',
	        store: Ext.create('Ext.data.Store', {  
			        model: 'State',  
			        data: [  
				        { "value": "AND", "text": "并且"},  
				        { "value": "OR", "text": "或者"}
				    ]
		    }),  
	        queryMode: 'local',
	        editable: false
	    });
	    //查询方式  
	    var expression_combo = Ext.create('Ext.form.field.ComboBox', {  
	    	displayField: 'text',
	        valueField: 'value', 
	        store: Ext.create('Ext.data.Store', {  
			        model: 'State',  
			        data: [  
				        { "value": "=", "text": "等于"},  
				        { "value": ">", "text": "大于"},
				        { "value": ">=", "text": "等于等于"},
				        { "value": "<", "text": "小于"},
				        { "value": "<=", "text": "小于等于"},
				        { "value": "LIKE", "text": "模糊匹配"},
				        { "value": "<>", "text": "不等于"}
				    ]
		    }),  
	        queryMode: 'local',  
	        typeAhead: true,
	        editable: false
	    });
	    //查询字段
	    var fieldlist = new Array();
	    for(i in this.columnHeaderMeta){
	    	var field = this.columnHeaderMeta[i];
	    	if(!field.fieldName){
	    		continue;
	    	}
	    	fieldlist.push({
	    		"value": field.fieldName,
	    		"text": field.text
	    	});
	    	
	    }
	    var field_combo = Ext.create('Ext.form.field.ComboBox', {  
	    	displayField: 'text',
	        valueField: 'value', 
	        store: Ext.create('Ext.data.Store', {  
			        model: 'State',  
			        data: fieldlist,
			        fields: ['value', 'text']
		    }),
		    id: "combo_field",
		    name: "combo_field",
	        queryMode: 'local',  
	        typeAhead: true,
	        editable: false
	    });
	    
	    /**
	     * 动态切换查询条件选择项
	     */
	    function changeCellBox(e){
    		if(e.colIdx == 5){
    			var record = queryGridPanel.getStore().getAt(e.rowIdx);
    			var column_field = record.get("field");
    			if(Ext.isEmpty(column_field)){
    				return;
    			}
				var col = queryGridPanel.columnManager.getColumns()[5];
				var field_box = super_grid.queryColumnField[column_field];
				var xtype = field_box.getXType();
				var field = null;
				if(xtype == 'select'){
					field = Ext.create("Ext.com.bkfm.combobox",{
						objPath: field_box.objPath,
						type: 'objPath',
						loadingText:'加载中……',
						editable: false
					});
				}else if(xtype == 'datefield'){
					field = Ext.create('Ext.form.field.Date',{
						format: field_box.format,
						editable: false
					});
				}else if(xtype == 'tree'){
					field = Ext.create("Ext.com.bkfm.comboboxtree", {
				        checkModel:'single',
				        treeConfigId: field_box.treeConfigId,
				        rootId: field_box.rootId,
				        treeNodeParameter : {

				        },
				        editable: false
				    });
				}else{
					field = Ext.create('Ext.form.field.Text',{
					});
				}
				col.setEditor(field);
    			record.isCreatEditor = true;
    			record.editorField = column_field;
    			e.record.set("field_value", "");
        		e.record.set("field_value_display", "");
    		}
	    }
	    
	    //创建表格  
	    var queryGridPanel = new Ext.grid.GridPanel({  
	        autoHeight:true,  
	        store: new Ext.data.ArrayStore({  
		        data: [],  
		        fields:[{name:'rule'}, 
		           {name:'rule_display'},  
		           {name:'field'},
		           {name:'field_display'},
		           {name:'expression'},
		           {name:'expression_display'},
		           {name:'field_value'},
		           {name:'field_value_display'}
		        ]  
		    }),  
		    selModel: Ext.create("Ext.selection.CheckboxModel", {
			    injectCheckbox: 1,//checkbox位于哪一列，默认值为0
			    mode: "multi",//multi,simple,single；默认为多选multi
			    checkOnly: false,//如果值为true，则只用点击checkbox列才能选中此条记录
			    allowDeselect: true,//如果值true，并且mode值为单选（single）时，可以通过点击checkbox取消对其的选择
			    enableKeyNav: true
			}),
	        columns: [new Ext.grid.RowNumberer({width:30}),
	        	{header:'规则',dataIndex:'rule_display',width:150,editor:rule_combo},
	        	{header:'查询字段',dataIndex:'field_display',width:150,editor:field_combo},
	        	{header:'表达式',dataIndex:'expression_display',width:150,editor:expression_combo},
	        	{header:'查询值',dataIndex:'field_value_display',width:150,editor:true}
	        	], 
	        listeners:{
	        	beforeedit: function (editor, e, eOpts){
	        		changeCellBox(e);
	        	},
	        	edit : function(editor, e) {
	        		if(e.colIdx == 5){
	        			//查询值
		            	var xtype = e.column.getEditor().getXType();
		            	if(xtype=="select"){
		            		e.record.set("field_value",e.column.getEditor().getValue());
		            		//e.record.set("field_value_display", e.column.getEditor().getDisplayValue());
		            		e.record.set("field_value_display", e.column.getEditor().getRawValue());
		            	}else if(xtype=="tree"){
		            		e.record.set("field_value",e.column.getEditor().getValue());
		            		//e.record.set("field_value_display", e.column.getEditor().getDisplayValue());
		            		e.record.set("field_value_display", e.column.getEditor().getRawValue());
		            	}else if(xtype=="datefield"){
		    				e.record.set("field_value",e.column.getEditor().getRawValue());
		    				e.record.set("field_value_display",e.column.getEditor().getRawValue());
		            	}else{
		            		e.record.set("field_value", e.column.getEditor().getValue());
		            		e.record.set("field_value_display", e.column.getEditor().getValue());
		            	}
	        		}else if(e.colIdx == 3){
	        			//字段名
	        			e.record.set("field",e.column.getEditor().getValue());
	            		//e.record.set("field_display", e.column.getEditor().getDisplayValue());
	            		e.record.set("field_display", e.column.getEditor().getRawValue());
	            		//changeCellBox(e);
	        		}else if(e.colIdx == 4){
	        			//字段名
	        			e.record.set("expression",e.column.getEditor().getValue());
	            		//e.record.set("field_display", e.column.getEditor().getDisplayValue());
	            		e.record.set("expression_display", e.column.getEditor().getRawValue());
	            		//changeCellBox(e);
	        		}else if(e.colIdx == 2){
	        			//字段名
	        			e.record.set("rule",e.column.getEditor().getValue());
	            		//e.record.set("field_display", e.column.getEditor().getDisplayValue());
	            		e.record.set("rule_display", e.column.getEditor().getRawValue());
	            		//changeCellBox(e);
	        		}
	            }
	        },
	        selType: 'cellmodel',  
	        plugins:[  
	                 Ext.create('Ext.grid.plugin.CellEditing',{  
	                     clicksToEdit:1 //设置单击单元格编辑  
	                 })  
	        ],  
	        tbar:['-',{  
	            text:'添加',  
	            iconCls: 'add',
	            handler:function(){  
	                var p ={  
	                        id:'',  
	                        name:'',  
	                        descn:''  
	                        }; 
	                	var store = queryGridPanel.getStore();
	                    store.insert(store.getCount(),p);  
	                }  
	            },'-',{  
	                text:'删除',  
	                iconCls: 'delete',
	                handler:function(){  
	                    Ext.Msg.confirm('系统提示','确定要删除？',function(btn){  
	                        if(btn=='yes'){  
	                        	var store = queryGridPanel.getStore();
	                        	var records = queryGridPanel.getSelectionModel().getSelection();
	                        	for(i in records){
	                        		var record = records[i];
	                        		store.remove(record);
	                        	}
	                        }  
	                    });  
	                }  
	        },'-',{
	        	text: '查询',
	        	iconCls: 'search',
	        	handler: function(){
	        		var records =  queryGridPanel.getStore().getModifiedRecords();
	        		var filter = "";
	        		var is_filter = true;
	        		for(i in records){
	        			var record = records[i];
	        			var rule = record.get("rule");
	        			var field_name = record.get("field");
	        			var expression = record.get("expression");
	        			var field_value = record.get("field_value");
	        			if(i==0){
	        				rule = "";
	        				if(field_name=="" || expression=="" || field_value==""){
	        					AjaxUtils.showError("第【"+(parseInt(i)+1)+"】,行查询条件不合法,请填写完整!");
	        					is_filter = false;
	        					break;
	        				}
	        			}else{
	        				if(rule=="" || field_name=="" || expression=="" || field_value==""){
	        					AjaxUtils.showError("第【"+(parseInt(i)+1)+"】,行查询条件不合法,请填写完整!");
	        					is_filter = false;
	        					break;
	        				}
	        			}
	        			if(expression == 'LIKE'){
	        				filter += rule + " "+field_name+ " "+expression+" '%"+field_value+"%' ";
	        			}else{
	        				filter += rule + " "+field_name+ " "+expression+" '"+field_value+"' ";
	        			}
	        		}
	        		if(!is_filter){
	        			return ;
	        		}
	        		super_grid.search(filter);
	        		//清空查询条件
	        		//var store = queryGridPanel.getStore();
	        		//store.removeAll();
	        		super_grid.query_win.close();
	        	}
	        },'->',{
	        	text: "关闭",
	        	iconCls: "close",
	        	handler: function(self){
	        		super_grid.query_win.close();
	        	}
	        }]  
	    });
	    
		this.query_win = Ext.create('Ext.com.bkfm.window', {
		    title: '高级查询',
		    autoScroll : true,
			modal : true,
		    height : Utils.getHeight()/2,
			width : Utils.getWidth()/2 + 100,
		    closeAction: 'hide',
		    items: queryGridPanel
		}).show(); 
	}
});